<?php

	class Ajax extends CI_Controller
	{
		public function __construct()
		{
			parent::__construct();
			
			$this->load->library('session');
			$this->load->database();
			$this->load->model('users_model', 'users');
		}
		
		public function do_login()
		{
			if($this->input->is_ajax_request())
			{
				$email = $this->input->post('email');
				$password = md5($this->input->post('password'));
				
				$result = $this->db->get_where('users', array('email' => $email, 'password' => $password));
				
				// OK
				if($result->num_rows() > 0)
				{
                                        // Get profile
                                        $user = $this->users->get_by_email($email);
                                        
					// Set sessions
					$this->session->set_userdata('logged_in', TRUE);
                                        $this->session->set_userdata('profile', serialize($user));
					
					echo json_encode(array('result' => 1));
				}
				// No matches found!
				else
				{
					echo json_encode(array('result' => 0));
				}
			}
		}
		
		public function do_signup()
		{
			if($this->input->is_ajax_request())
			{
				$email = $this->input->post('email');
				$password = $this->input->post('password');
				
				// Connect?
				if($this->session->userdata('connect'))
				{
					$connect_data = $this->session->userdata('connect');
					
					// If user wants to connect by using twitter
					if(array_key_exists('twitter_id', $connect_data))
					{
						$twitter_id = $connect_data['twitter_id'];
						
						// Check if user exits...
						$result = $result = $this->db->get_where('users', array('email' => $email, 'password' => md5($password)));
						if($result->num_rows() > 0)
						{
							$user = $result->row();
							
							// User exists, update.
							$user->twitter_id = $twitter_id;
							$this->users->update($user);
							
							// Remove connect session
							$this->session->unset_userdata('connect');
							
							// Set session
							$this->session->set_userdata('logged_in', TRUE);
                                                        $this->session->set_userdata('profile', serialize($user));
							
							echo json_encode(array('result' => 1));
							return;
							
						}
						// If doesn't, proceed with usual sign up.
					}	
				}		
				
				
				// Valid email address?
				if(preg_match("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^", $email))
				{				
					$result = $this->users->get_by_email($email);
					
					// We have a match!
					if($result)
					{
						echo json_encode(array('result' => 0));
					}
					// No matches found, feel free to use.
					else
					{
						// Connect?
						if($this->session->userdata('connect'))
						{
							// If user wants to connect by using twitter
							if(array_key_exists('twitter_id', $connect_data))
							{
								$twitter_id = $connect_data['twitter_id'];
								$result = $this->users->add($email, md5($password), NULL, NULL, $twitter_id);
							}
							// Facebook / Google
							else
							{
								$result = $this->users->add($email, md5($password));
							}
							// Was insert successful?
							if($result)
							{
								// Remove connect session
								$this->session->unset_userdata('connect');
								
								// Set session
								$this->session->set_userdata('logged_in', TRUE);
                                                                $this->session->set_userdata('profile', serialize($this->users->get_by_email($email)));
								
								echo json_encode(array('result' => 1));
							}
						}
						else
						{	
							// Was insert successful?
							if($this->users->add($email, md5($password)))
							{
								// Set session
								$this->session->set_userdata('logged_in', TRUE);
                                                                $this->session->set_userdata('profile', serialize($this->users->get_by_email($email)));
								
								echo json_encode(array('result' => 1));
							}
						}
					}
				}
				// Email not valid
				else
				{
					echo json_encode(array('result' => -1, 'extra' => $this->input->post('email')));
				}
			}
		}
                
                public function get_categories()
                {
                    if($this->input->is_ajax_request())
                    {
                        try
                        {
                            // Load library
                            $this->load->library('FocusLib');

                            // Arguments
                            $provider_slug = $this->input->post('provider');
                            $category_id = $this->input->post('ID');

                            // Build provider
                            $provider = $this->focuslib->getProvider($provider_slug);
                            $category = $provider->getCategoryByID($category_id);
                            
                            if($category)
                            {
                                // Get supported parameters
                                $parameters = $category->getSupportedParameters();

                                if($parameters)
                                {
                                    // Prepare && send parameters
                                    $result = array('result' => array());
                                    
                                    foreach ($parameters as $parameter)
                                    {
                                        $result['result'] []= $parameter->getJSONFriendlyNotation();
                                    }
                                    
                                    echo json_encode($result);
                                }
                                else
                                {
                                    echo json_encode(array('result' => -1));
                                }
                            }
                            else
                            {
                                echo json_encode(array('result' => -1));
                            }
                        }
                        catch ( Exception $exc )
                        {
                            log_message('error', $exc->getTraceAsString());
                            echo json_encode(array('result' => -1));
                        }
                                            
                    }
                }
                
                public function add_filter($editID = NULL)
		{
			if($this->input->is_ajax_request())
			{
                            try
                            {
                                $result = array();
                                
                                // Load library
                                $this->load->library('FocusLib');
                                
                                // Get available providers
                                $providers = $this->focuslib->listProviders();
                                
                                // For each provider create array of parameters
                                // (if posted)
                                foreach ($providers as $provider)
                                {
                                    // Category selected?
                                    if($this->input->post( 'categories-' . $provider->slug ))
                                    {
                                        // Instantiate category
                                        $category = $provider->getCategoryByID
                                        (
                                                $this->input->post( 'categories-' . $provider->slug )
                                        );
                                        
                                        if($category)
                                        {
                                            // Construct bundle
                                            $bundle['providerName'] = $provider->slug;
                                            $bundle['categoryID'] = $this->input->post( 'categories-' . $provider->slug );
                                            $bundle['parameters'] = array();
                                            
                                            // Get supported parameters
                                            $parameters = $category->getSupportedParameters();
                                            foreach ($parameters as $parameter)
                                            {
                                                // Scalar parameters
                                                if( $this->input->post( $provider->slug . '-' . $parameter->slug ) )
                                                {
                                                    switch ( $parameter->type )
                                                    {
                                                        case FParameter::TYPE_SINGLE:
                                                            $bundle['parameters'][$parameter->slug] =
                                                                    $this->input->post( $provider->slug . '-' . $parameter->slug );
                                                            break;
                                                        case FParameter::TYPE_BOOL:
                                                            $bundle['parameters'][$parameter->slug] = TRUE;
                                                            break;
                                                        case FParameter::TYPE_SET:
                                                            $bundle['parameters'][$parameter->slug] =
                                                                    $this->input->post( $provider->slug . '-' . $parameter->slug );
                                                            break;
                                                    }
                                                }
                                                
                                                // Interval parameters
                                                if( $this->input->post( $provider->slug . '-min-' . $parameter->slug ) )
                                                {
                                                    switch ( $parameter->type )
                                                    {
                                                        // Safety
                                                        case FParameter::TYPE_INTERVAL:
                                                            if(  array_key_exists( $parameter->slug, $bundle['parameters'] ) )
                                                            {
                                                                $bundle['parameters'][$parameter->slug]['minimum'] = 
                                                                        $this->input->post( $provider->slug . '-min-' . $parameter->slug );
                                                            }
                                                            else
                                                            {
                                                                $bundle['parameters'][$parameter->slug] = array(
                                                                    'minimum' => $this->input->post( $provider->slug . '-min-' . $parameter->slug ),
                                                                    'maximum' => ''
                                                                );         
                                                            }
                                                            break;
                                                    }
                                                }
                                                
                                                if( $this->input->post( $provider->slug . '-max-' . $parameter->slug ) )
                                                {
                                                    switch ( $parameter->type )
                                                    {
                                                        // Safety
                                                        case FParameter::TYPE_INTERVAL:
                                                            if(  array_key_exists( $parameter->slug, $bundle['parameters'] ) )
                                                            {
                                                                $bundle['parameters'][$parameter->slug]['maximum'] = 
                                                                        $this->input->post( $provider->slug . '-max-' . $parameter->slug );
                                                            }
                                                            else
                                                            {
                                                                $bundle['parameters'][$parameter->slug] = array(
                                                                    'maximum' => $this->input->post( $provider->slug . '-max-' . $parameter->slug ),
                                                                    'minimum' => ''
                                                                );         
                                                            }
                                                            break;
                                                    }
                                                }
                                            }
                                            
                                            $bundle['currentPosition'] = '';
                                            
                                            $result []= $bundle;
                                        }
                                    }
                                }
                                
                                // Title / interval / email-notification
                                $title = $this->input->post('title');
                                $interval = $this->input->post('interval');      
                                $sendByEmail = $this->input->post('sendByEmail');     
                                
                                // Load model and save
                                $this->load->model('filters_model', 'filters');
                                
                                // Update instead
                                if($editID != NULL)
                                {
                                    $filter = $this->filters->get($editID);
                                    if($filter)
                                    {
                                        // User owns the filter?
                                        $profile = unserialize($this->session->userdata('profile'));
                                        if($profile->ID == $filter->clientID)
                                        {
                                            $filter->title = $title;
                                            $filter->interval = $interval;
                                            $filter->filterData = json_encode( $result );
                                            $filter->sendByEmail = $sendByEmail;
                                            
                                            $this->filters->update($filter);
                                            
                                            echo json_encode(
                                                array(
                                                    'result' => 1,
                                                    'debug' => $result
                                                )
                                             );
                                        }
                                        else
                                        {
                                            echo json_encode(
                                                array(
                                                    'result' => 0,
                                                    'debug' => $result
                                                )
                                             ); 
                                        }
                                    }
                                    else
                                    {
                                        echo json_encode(
                                               array(
                                                   'result' => 0,
                                                   'debug' => $result
                                               )
                                            );   
                                    }
                                }
                                
                                // Add new
                                else
                                {
                                    // Was insert successful?
                                    // TODO: Remove debug output
                                    if($this->filters->add($title, $interval, $result, $sendByEmail))
                                    {
                                        echo json_encode(
                                                array(
                                                    'result' => 1,
                                                    'debug' => $result
                                                )
                                             );
                                    }
                                    else
                                    {
                                        echo json_encode(
                                                array(
                                                    'result' => 0,
                                                    'debug' => $result
                                                )
                                             );    
                                    }
                                }
                            }
                            catch ( Exception $exc )
                            {
                                echo $exc->getTraceAsString();
                            }
                        }
                }
	
                public function delete_filter()
		{
			if($this->input->is_ajax_request())
			{
                            $ID = $this->input->post('ID');

                            // Load models
                            $this->load->model('filters_model', 'filters');
                            $this->load->model('content_model', 'content');
                            
                            // Filter exists?
                            $filter = $this->filters->get($ID);
                            if($filter)
                            {
                                // User owns the filter?
                                $profile = unserialize($this->session->userdata('profile'));
                                if($profile->ID == $filter->clientID)
                                {
                                    // Delete
                                    // TODO: Probably should clean up everything in cache as well.
                                    if($this->filters->delete($filter))
                                    {
                                        // Delete content associateted to current filter
                                        $this->content->deleteFilterContent($filter->ID);
                                        echo json_encode(array('result' => 1));
                                    }
                                    else
                                    {
                                        echo json_encode(array('result' => 0));
                                    }
                                }
                                else
                                {
                                   echo json_encode(array('result' => 0)); 
                                }
                            }
                            else
                            {
                                echo json_encode(array('result' => 0));
                            }
                        }
                }
        
                public function get_content()
                {
                    if($this->input->is_ajax_request())
                    {
                        // Filter ID
                        if($this->input->post('id'))
                            $filter_id = $this->input->post('id');
                        else
                            $filter_id = NULL;
                        
                        // Provider name
                        if($this->input->post('provider'))
                            $provider_name = $this->input->post('provider');
                        else
                            $provider_name = NULL;
                        
                        // Start & offset
                        if($this->input->post('count'))
                            $count = $this->input->post('count');
                        else
                            $count = 10;
                        
                        if($this->input->post('offset'))
                            $offset = $this->input->post('offset');
                        else
                            $offset = 0;

                        $this->load->model('content_model', 'content');
                        
                        $result = array();
                        $content = $this->content->get_latest($filter_id, $provider_name, $count, $offset);
                        if($content)
                        {
                            foreach ($content as $value)
                            {
                                array_push($result, $value);
                            }
                        }   
                        
                        echo json_encode($result);
                    }
                }
        
                public function delete_content()
                {
                    if($this->input->is_ajax_request())
                    {
                        $items = $this->input->post('items');
                        if($items)
                        {
                            // Models
                            $this->load->model('content_model', 'content');
                            $this->load->model('filters_model', 'filters');
                            
                            // User
                            $user = unserialize($this->session->userdata('profile'));
                            
                            foreach ($items as $id)
                            {
                                $content = $this->content->get($id);
                                if($content)
                                {
                                    $filter = $this->filters->get($content->filterID);
                                    if($filter && $filter->clientID == $user->ID)
                                    {
                                         $this->content->delete($content);
                                    }
                                    else
                                    {
                                        die(json_encode(array('result' => 0)));
                                    }
                                }
                                else
                                {
                                    die(json_encode(array('result' => 0)));
                                }
                            }
                            
                            echo json_encode(array('result' => 1));
                        }
                        else
                        {
                            echo json_encode(array('result' => 0));
                        }
                    }
                }
        }

?>